<template>
    <div>
        <div class="main_operation">
            <div class="operation_left">
                <a-button v-if="routerShow($route,'passport_register')" class="mr10" type="primary" @click="addBtn">添加</a-button>
                <!-- <a-button class="mr10" type="danger" @click="addBtn">批量删除</a-button> -->
            </div>
            <div class="operation_right">
                <a-select v-model="searchVal" allowClear class="mr10" style="width: 250px" placeholder="请选择搜索类型">
                    <a-select-option value="username">用户名</a-select-option>
                    <a-select-option value="name">用户姓名</a-select-option>
                    <a-select-option value="phone">用户手机</a-select-option>
                    <a-select-option value="agent_name">代理名称</a-select-option>
                    <a-select-option value="company_name">公司名称</a-select-option>
                    <a-select-option value="role_name">角色名称</a-select-option>
                </a-select>
                <a-input-search v-model="searchInp" class="mr10" placeholder="请输入查询内容" @search="val => onSearch(val, 'input')" enterButton="查询" />
                <a-button type="danger" @click="val => onSearch(val, 'all')">重置</a-button>
            </div>
        </div>
        <div class="main">
            <a-table :pagination="false" :columns="Fields" :loading="tableLoad" :dataSource="dataLists.data" :rowKey="record => record.id" :scroll="{x: 1900, y: 500 }">
                <template slot="activation_status" slot-scope="text, record">
                    <a-button v-if="record.activation_status == '未激活'" size="small" type="primary" class="btn-warning" @click="activationBtn(record)">{{text}}</a-button>
                    <a-button v-else size="small" class="btn-success" @click="()=>$message.success(`账号状态：${text}`)" type="primary">{{text}}</a-button>
                </template>
                <template slot="action" slot-scope="text, record">
                    <a-button v-if="routerShow($route,'passport_password')" size="small" class="mr5 mb5 btn-warning" type="primary" @click="passBtn(record)">修改密码</a-button>
                    <a-button v-if="routerShow($route,'passport_update')" size="small" class="mb5" type="primary" @click="editBtn(record)">编辑</a-button>
                    <a-button v-if="routerShow($route,'wechat_WxUntyingUser')" size="small" class="mr5 mb5 btn-success" type="primary" :disabled="record.wx_openid != '' && record.wx_openid != null ? false : true" @click="untyingBtn(record)"> {{record.wx_openid != '' && record.wx_openid != null ? '微信解绑' : '未绑微信'}}</a-button>
                    <a-button v-if="routerShow($route,'passport_delete')" class="mb5" size="small" type="danger" @click="delBtn(record)">删除</a-button>
                </template>
            </a-table>
            <div class="pageBox">
                <a-pagination :total="dataLists.total" :showTotal="total => `共 ${total} 条数据`" :pageSize="dataLists.per_page" :defaultCurrent="1" @change="pageChange" />
            </div>
        </div>
        <a-modal :maskClosable="false" :title="titleModel" v-model="visible" :width="600" :confirmLoading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
            <a-form>
                <a-form-item required label="用户名:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formItem.username" placeholder="请输入用户名（用于登录系统）" />
                </a-form-item>
                <a-form-item v-if="passShow" required label="初始密码:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formItem.password" placeholder="请输入初始密码" />
                </a-form-item>
                <a-form-item required label="用户等级:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-radio-group v-model="formItem.rank_type" name="rank_type">
                        <a-radio :value="1">管理员</a-radio>
                        <a-radio :value="2">普通用户</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item required label="用户姓名:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formItem.name" placeholder="请输入用户姓名" />
                </a-form-item>
                <a-form-item required label="手机号码:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formItem.phone" placeholder="请输入手机号码" />
                </a-form-item>
                <a-form-item label="邮箱:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formItem.email" placeholder="请输入邮箱" />
                </a-form-item>
                <!-- <a-form-item label="公司名称:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 12,xs:24 }">
          <a-input v-model="formItem.company" style="width: 300px" placeholder="请输入公司名称" />
        </a-form-item>
        <a-form-item label="公司地址:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 12,xs:24 }">
          <a-input v-model="formItem.company_address" style="width: 300px" placeholder="请输入公司地址" />
        </a-form-item>-->
                <a-form-item required label="关联角色:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-select v-model="formItem.role" placeholder="请选择角色">
                        <a-select-option v-for="item in roleAllData" :value="item.id" :key="item.id">{{item.role_name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item required label="用户类型:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <!-- <a-radio-group :options="plainOptions" v-model="userType" @change="onChange" /> -->
                    <a-radio-group @change="onChange" v-model="userType">
                        <a-radio :value="1" v-if="grade=== 1">平台</a-radio>
                        <a-radio :value="2" v-if="grade === 1 || grade === 2 ">代理</a-radio>
                        <a-radio :value="3" v-if="grade === 1 || grade ===2 || grade ===3">公司</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item required :label="isType" v-if="userType != 1" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-select v-model="formItem.company" @change="onSelect" allowClear :placeholder="`请选择账号${isType}` ">
                        <a-select-option v-for="item in selectData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <!-- <a-form-item required label="所属公司:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
          <a-cascader
            changeOnSelect
            v-model="groupId"
            :fieldNames="{ label: 'name', value: 'id', children: 'parent' }"
            @change="onChange"
            :options="groupData"
            placeholder="请选择所属公司"
          />
        </a-form-item> -->
                <!-- <a-form-item
          required
          v-if="groupId.length>1"
          label="所属上级:"
          :label-col="{ md: 5,xs:24 }"
          :wrapper-col="{ md: 18,xs:24 }"
        >
          <a-select v-model="formItem.sup_user" placeholder="所属上级">
            <a-select-option v-for="item in setuserSupUserData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
          </a-select>
        </a-form-item> -->
                <a-form-item v-if="userType == 3 && formItem.company != undefined" label="关联设备:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-select v-model="formItem.associated_device" placeholder="设备名称">
                        <a-select-option v-for="item in groupEquipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <!-- <a-form-item required label="关联组态:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 12,xs:24 }">

<a-select class="mr10" style="width: 300px" placeholder="请选择关联组态">

<a-select-option value="1">预留功能</a-select-option>

<a-select-option value="2">预留功能</a-select-option>

<a-select-option value="3">预留功能</a-select-option>

</a-select>
        </a-form-item>-->
            </a-form>
        </a-modal>
        <a-modal title="修改密码" v-model="passVisible" :width="500" :confirmLoading="confirmLoading" @ok="passOk" @cancel="passCancel">
            <a-form>
                <a-form-item required label="旧密码:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formPass.old_password" placeholder="请输入旧密码" />
                </a-form-item>
                <a-form-item required label="新密码:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formPass.password" placeholder="请输入新密码" />
                </a-form-item>
                <a-form-item required label="确认密码:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="formPass.c_password" placeholder="请再次输入新密码" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import {
  mapState,
  mapActions,
} from 'vuex';
import Vue from 'vue';
import {
  USER,
} from '@/store/mutation-types';

const plainOptions = [{
  label: '平台',
  value: 1,
},
{
  label: '代理',
  value: 2,
},
{
  label: '公司',
  value: 3,
},
];
export default {
  name: 'userList',
  data() {
    return {
      grade: '',
      plainOptions,
      userType: 1,
      selectData: [],
      searchVal: undefined,
      searchInp: '',
      groupId: [],
      formList: {
        // username: '',
        // name: '',
        // phone: '',
        page: 1,
      },
      titleModel: '', // 添加编辑窗口标题
      visible: false, // 添加编辑窗口开关
      passVisible: false, // 修改密码窗口开关
      confirmLoading: false, // 添加编辑按钮状态
      passShow: true, // 初始密码显示隐藏
      tableLoad: false, // 列表loading状态

      // 添加编辑
      formItem: {
        username: '', // 用户名，必填
        password: '', // 初始密码，必填
        associated_device: undefined, // 关联设备ID
        rank_type: 2,
        email: '', // 邮箱
        name: '', // 用户姓名
        phone: '', // 手机
        role: '', // 管理角色ID
        company: undefined, // 所属公司
        sup_user: '', // 所属上级ID
      },

      // 修改密码
      formPass: {
        id: '', // id
        old_password: '', // 旧密码
        password: '', // 新密码
        c_password: '', // 2次新密码
      },
    };
  },
  computed: {
    ...mapState({
      Fields: state => state.Passport.userFields,
      dataLists: state => state.Passport.userLists,
      requestCode: state => state.Passport.requestCode,

      setuserSupUserData: state => state.Passport.setuserSupUserData, // 上级分类
      passportAllData: state => state.Passport.passportAllData, // 所有用户信息
      roleAllData: state => state.Role.roleAllData, // 所有角色
      groupEquipmentData: state => state.equipment.groupEquipmentData, // 公司查设备
      // groupData: state => state.group.groupData,
      agentAllData: state => state.group.agentAllData, // 代理all信息
      companyAllData: state => state.group.companyAllData, // 公司all信息
    }),
    isType() {
      if (this.userType == 1) {
        // this.selectData = this.userPlatformAll
        return '所属平台';
      }
      if (this.userType == 2) {
        this.selectData = this.agentAllData;
        return '所属代理';
      }
      if (this.userType == 3) {
        this.selectData = this.companyAllData;
        return '所属公司';
      }
    },
  },
  mounted() {
    if (this.$route.query.agentID != undefined) {
      this.formList.company = this.$route.query.agentID;
    }
    if (this.$route.query.CompanyID != undefined) {
      this.formList.company = this.$route.query.CompanyID;
    }
    // this.groupAll();
    this.agentAll(); // 代理all信息
    this.companyAll(); // 公司all信息
    this.roleAll();
    this.changeData();
    console.log(Vue.ls.get(USER));
    const {
      grade,
    } = Vue.ls.get(USER);
    this.grade = grade;
  },
  methods: {
    activationBtn(item) {
      if (!this.routerShow(this.$route, 'passport_upActivationStatus')) {
        this.$error({
          title: '您没有权限，无法激活账号，请联系管理员',
        });
        return null;
      }
      const that = this;
      console.log(item);
      this.$confirm({
        title: '确定激活该用户吗？',
        content: `用户名: ${item.username}`,
        okText: '确定激活',
        onOk() {
          that.UserActivation(item.id);
          that.changeData();
        },
      });
    },
    ...mapActions({
      userLists: 'Passport/userLists', // 列表
      addUser: 'Passport/addUser', // 添加
      editUser: 'Passport/editUser', // 编辑
      changePass: 'Passport/changePass', // 修改密码
      delUser: 'Passport/delUser', // 删除
      wxUntyingUser: 'Passport/wxUntyingUser', // 解绑微信
      UserActivation: 'Passport/UserActivation', // 账号激活
      userSupUser: 'Passport/userSupUser', // 上级用户信息
      passportAll: 'Passport/passportAll', // 所有用户信息
      roleAll: 'Role/roleAll', // 所有角色
      groupEquipmentAll: 'equipment/groupEquipmentAll', // 根据公司查询设备
      // groupAll: 'group/groupAll', // 设备分组信息
      agentAll: 'group/agentAll', // 代理all信息
      companyAll: 'group/companyAll', // 公司all信息
    }),
    // 重新获取列表数据
    changeData() {
      this.tableLoad = true;
      setTimeout(() => {
        // this.passportAll();
        this.userLists(this.formList);
        this.tableLoad = false;
      }, 1000);
    },
    // 搜索
    onSearch(val, type) {
      const { searchVal } = this;
      this.formList = {
        page: 1,
      };
      if (type == 'input') {
        if (val == '') return null;
        if (searchVal == 'username') {
          this.formList.username = val;
        } else if (searchVal == 'name') {
          this.formList.name = val;
        } else if (searchVal == 'phone') {
          this.formList.phone = val;
        } else if (searchVal == 'agent_name') {
          this.formList.agent_name = val;
        }else if (searchVal == 'company_name') {
          this.formList.company_name = val;
        }else if (searchVal == 'role_name') {
          this.formList.role_name = val;
        }
      } else if (type == 'all') {
        this.searchVal = undefined;
        this.searchInp = '';
      }
      this.changeData();
    },
    onChange(e) {
      this.formItem.company = undefined;
    },
    onSelect(val) {
      console.log(val);
      if (this.userType == 3) {
        this.formItem.associated_device = undefined;
        this.groupEquipmentAll({
          group_id: val,
        });
      }
    },
    // 分组选择
    // onChange(value) {
    //   console.log(value);
    //   this.formItem.company = value[value.length - 1];
    //   if (value.length >= 2) {
    //     this.userSupUser(value[value.length - 1]);
    //   }
    //   if (value.length == 3) {
    //     this.groupEquipmentAll({
    //       group_id: value[2],
    //     });
    //   }
    // },
    /* *删除* */
    // *删除按钮
    delBtn(item) {
      const _this = this;
      console.log(item);
      this.$confirm({
        title: `您确定要删除 ${item.username} 吗?`,
        content: '删除后将不可恢复,请仔细核对确认!',
        okText: '是的',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          _this.delUser(item.id);
          _this.changeData();
        },
        onCancel() {},
      });
    },
    // 微信解绑
    untyingBtn(item) {
      const _this = this;
      console.log(item);
      this.$confirm({
        title: `您确定要解绑 ${item.username} 吗?`,
        content: `解绑微信后将无法使用微信号 ${item.nickName} 登录该账号`,
        okText: '是的',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          _this.wxUntyingUser(item.id);
          _this.changeData();
        },
        onCancel() {},
      });
    },
    /* *修改密码* */
    passBtn(item) {
      this.formPass = {
        id: item.id, // id
        old_password: '', // 旧密码
        password: '', // 新密码
        c_password: '', // 2次新密码
      };
      this.passVisible = true;
    },
    //* 修改密码确定
    passOk() {
      this.confirmLoading = true;
      this.changePass(this.formPass);
      setTimeout(() => {
        if (this.requestCode === 0) {
          this.passVisible = false;
        }
        this.confirmLoading = false;
      }, 1000);
    },
    //* 取消
    passCancel() {
      this.visible = false;
      this.formItem = {
        id: '', // id
        old_password: '', // 旧密码
        password: '', // 新密码
        c_password: '', // 2次新密码
      };
    },
    /* 修改密码end */

    /* *添加编辑* */
    //* 添加按钮
    addBtn() {
      this.titleModel = '添加用户';
      this.formItem = {
        username: '', // 用户名，必填
        password: '', // 初始密码，必填
        associated_device: undefined, // 关联设备ID
        company: undefined, // 公司名称
        // company_address: "", //公司地址
        rank_type: 2,
        email: '', // 邮箱
        name: '', // 用户姓名
        phone: '', // 手机
        // // role: "", //管理角色ID
        // sup_user: "" //上级分类ID
      };
      this.groupId = [];
      this.passShow = true; // 显示密码文本框
      this.visible = true;
    },
    //* 编辑按钮
    editBtn(item) {
      console.log(item);
      this.titleModel = '编辑用户';
      this.passShow = false; // 隐藏密码文本框
      delete this.formItem.password; // 删除密码文本框字段

      // 填充数据，打开窗口
      const arr = [];
      for (const i in item.group_ids) {
        arr.push(Number(item.group_ids[i])); // 属性
      }
      this.groupId = arr;
      // if (arr.length >= 2) {
      //   this.userSupUser(arr[arr.length - 1]);
      // }
      if (arr.length == 3) {
        this.groupEquipmentAll({
          group_id: item.company,
        });
      }
      this.formItem = {
        id: item.id,
        username: item.username,
        name: item.name,
        phone: item.phone,
        email: item.email,
        rank_type: item.rank_type,
        // company_address: item.company_address,
        role: Number(item.role),
        company: Number(item.company),
        associated_device: Number(item.associated_device),
        // sup_user: item.sup_user == null ? undefined : item.sup_user, // 上级分类ID
      };
      this.userType = item.grade;
      this.visible = true;
    },
    // 确定
    handleOk() {
      if (this.userType == 2) {
        if (this.formItem.company == undefined) {
          this.$notification.warning({
            message: '所属代理不能为空!',
          });
        } else {
          this.editUser(this.formItem);
          setTimeout(() => {
            if (this.requestCode === 0) {
              this.visible = false;
              this.changeData();
            }
            this.confirmLoading = false;
          }, 1000);
        }
      } else {
        this.confirmLoading = true;
        if (this.titleModel == '添加用户') {
          this.addUser(this.formItem);
        } else {
          this.editUser(this.formItem);
        }
        setTimeout(() => {
          if (this.requestCode === 0) {
            this.visible = false;
            this.changeData();
          }
          this.confirmLoading = false;
        }, 1000);
      }
    },
    // 取消
    handleCancel() {
      this.visible = false;
      this.userType = 1;
      this.formItem = {
        username: '', // 用户名，必填
        password: '', // 初始密码，必填
        associated_device: undefined, // 关联设备ID
        company: undefined, // 公司名称
        // company_address: "", //公司地址
        rank_type: 2,
        email: '', // 邮箱
        name: '', // 用户姓名
        phone: '', // 手机
        // // role: "", //管理角色ID
        // sup_user: "" //上级分类ID
      };
    },
    /* 添加编辑end */

    /* 页码 */
    pageChange(page) {
      this.formList.page = page;
      this.userLists(this.formList);
    },
  },
};
</script>

<style scoped>
</style>
